package com.cooksys.film_rental.controllers;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cooksys.film_rental.bo.CountryBo;
import com.cooksys.film_rental.bo.RegistrationFormBo;
import com.cooksys.film_rental.bo.StoreBo;
import com.cooksys.film_rental.model.Country;
import com.cooksys.film_rental.model.Store;
import com.cooksys.film_rental.model.forms.FilmSearchForm;
import com.cooksys.film_rental.model.forms.RegistrationForm;

@Controller
@SessionAttributes({ "filmSearchForm" })
public class RegistrationController {

	@Autowired
	RegistrationFormBo registrationFormBo;

	@Autowired
	StoreBo storeBo;

	@Autowired
	CountryBo countryBo;

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(ModelMap model) {

		return "registrationView";

	}

	@RequestMapping(value = "/register/submit", method = RequestMethod.POST)
	public String submitRegistration(
			@ModelAttribute("registrationForm") @Valid RegistrationForm registrationForm,
			BindingResult result, ModelMap model) {

		if (result.hasErrors()) {

			return "registrationView";

		} else {

			this.registrationFormBo.saveRegistration(registrationForm);

			return "registrationCompleteView";
		}

	}

	@ModelAttribute("registrationForm")
	private RegistrationForm initRegistrationForm() {

		RegistrationForm registrationForm = new RegistrationForm();

		return registrationForm;

	}

	@ModelAttribute("storeMap")
	private Map<String, String> populateStoreMap() {

		Map<String, String> storeIdToDisplayValueMapping = new LinkedHashMap<String, String>();

		List<Store> stores = storeBo.getAllStores();
		for (Store s : stores) {
			storeIdToDisplayValueMapping.put(s.getStoreId().toString(),
					"Store " + s.getStoreId());
		}

		return storeIdToDisplayValueMapping;

	}

	@ModelAttribute("countryMap")
	private Map<String, String> populateCountryMap() {

		Map<String, String> countryIdToDisplayValueMapping = new LinkedHashMap<String, String>();

		List<Country> countries = countryBo.getAllCountries();
		for (Country c : countries) {
			countryIdToDisplayValueMapping.put(c.getCountryId().toString(),
					c.getCountry());
		}

		return countryIdToDisplayValueMapping;

	}

	@ModelAttribute("filmSearchForm")
	private FilmSearchForm initFilmSearchForm() {
		FilmSearchForm filmSearchForm = new FilmSearchForm();
		return filmSearchForm;
	}

}
